package com.zc.framework.system;

import com.zc.framework.common.bean.AjaxResult;
import com.zc.framework.utils.DateUtils;
import com.zc.framework.web.validator.BeanValidators;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.FileEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zc on 2016/9/2.
 */
public abstract class BaseController extends MultiActionController {

    @Autowired
    protected Validator validator;


    /**
     * 成功,返回状态
     * @param success 状态true/false
     * @return
     */
    public AjaxResult success(Boolean success) {
        return new AjaxResult(success);
    }

    /**
     * 成功,返回状态
     * @param success 状态true/false
     * @return
     */
    public AjaxResult success(Boolean success, String message) {
        return new AjaxResult(success, message);
    }

    /**
     * 返回json数据
     * @param success 状态true/false
     * @param data 实体
     * @return
     */
    public AjaxResult json(Boolean success, Object data) {
        return new AjaxResult(success, data);
    }

    /**
     * 失败,返回状态及原因
     * @param success 状态true/false
     * @param message 消息
     * @return
     */
    public AjaxResult fail(Boolean success, String message) {
        return new AjaxResult(success, message);
    }

    /**
     * 转换为ajax需要的 JSON
     * @param success 状态
     * @param message 消息
     * @param entity  实体
     * @return
     */
    protected Map<String, Object> setJson(boolean success, String message, Object entity){
        Map<String,Object> json = new HashMap<String,Object>();
        json.put("success", success);
        json.put("message", message);
        json.put("entity", entity);
        return json;
    }

    /**
     * ajax成功/失败
     * @param success 状态
     * @return
     */
    protected Map<String, Object> setJson(boolean success){
        Map<String,Object> json = new HashMap<String,Object>();
        json.put("success", success);
        return json;
    }

    /**
     * ajax成功/失败 + 消息
     * @param success 状态
     * @param message 消息
     * @return
     */
    protected Map<String, Object> setJson(boolean success, String message){
        Map<String,Object> json = new HashMap<String,Object>();
        json.put("message", message);
        json.put("success", success);
        return json;
    }

    /**
     * 重定向至地址 url
     * @param url 请求地址
     * @return
     */
    protected String redirectTo( String url ) {
        StringBuffer rto = new StringBuffer("redirect:");
        rto.append(url);
        return rto.toString();
    }

    protected boolean beanValidator(Model model, Object object, Class... groups) {
        try {
            BeanValidators.validateWithException(this.validator, object, groups);
            return true;
        } catch (ConstraintViolationException var6) {
            List list = BeanValidators.extractPropertyAndMessageAsList(var6, ": ");
            list.add(0, "数据验证失败：");
            this.addMessage(model, (String[])list.toArray(new String[0]));
            return false;
        }
    }

    protected AjaxResult beanValidator(Object object, Class... groups) {
        AjaxResult ajaxResult = null;
        try {
            BeanValidators.validateWithException(this.validator, object, groups);
            return ajaxResult;
        } catch (ConstraintViolationException var6) {
            List<String> list = BeanValidators.extractPropertyAndMessageAsList(var6, ": ");
//            list.add(0, "数据验证失败：");
            ajaxResult = new AjaxResult(false,list.get(0));
            return ajaxResult;
        }
    }


    protected boolean beanValidator(RedirectAttributes redirectAttributes, Object object, Class... groups) {
        try {
            BeanValidators.validateWithException(this.validator, object, groups);
            return true;
        } catch (ConstraintViolationException var6) {
            List list = BeanValidators.extractPropertyAndMessageAsList(var6, ": ");
            list.add(0, "数据验证失败：");
            this.addMessage(redirectAttributes, (String[])list.toArray(new String[0]));
            return false;
        }
    }

    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        String[] var4 = messages;
        int var5 = messages.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String message = var4[var6];
            sb.append(message).append(messages.length > 1?"<br/>":"");
        }

        model.addAttribute("message", sb.toString());
    }

    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        String[] var4 = messages;
        int var5 = messages.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String message = var4[var6];
            sb.append(message).append(messages.length > 1?"<br/>":"");
        }

        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(text == null?null: StringEscapeUtils.escapeHtml4(text.trim()));
            }

            public String getAsText() {
                Object value = this.getValue();
                return value != null?value.toString():"";
            }
        });
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(DateUtils.parseDate(text));
            }
        });
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
        binder.registerCustomEditor(File.class, new FileEditor());
    }


}
